#!/bin/bash

set -eu

help() {
        echo "makec [OPTIONS] FILES"
        echo "For each FILE.mkc in FILES, compile it to FILE.c"
        echo "-g  Generate makec file place in C code for debug"
        echo "-c  Call C compiler to compile generated C code"
        echo "-r  Run result executable, implies -c"
        echo "-f  Force update, run compiler even if up to date"
        echo "-h  Print this help and exit"
}

main() {
        C=0
        G=0
        R=0
        F=0

        while [ $# -ne 0 ]; do
                case "$1" in
                -c)
                        C=1
                        shift
                        ;;
                -g)
                        G=1
                        shift
                        ;;
                -f)
                        F=1
                        shift
                        ;;
                -r)
                        R=1
                        C=1
                        shift
                        ;;
                -h)
                        help
                        exit
                        ;;
                -*)
                        echo "invalid option: $1" >&1
                        exit 1
                        ;;
                *) break ;;
                esac
        done

        cargo build -q

        for SOURCE; do
                case "$SOURCE" in
                *.mkc) ;;
                *)
                        echo "suffix of input file is not .mkc" >&2
                        exit 1
                        ;;
                esac

                case ${SOURCE} in
                /*) ;;
                *) SOURCE=./${SOURCE} ;;
                esac

                MAKEC_OPT=("$SOURCE")

                if [ $G -eq 1 ]; then
                        MAKEC_OPT+=(-g)
                fi

                C_TMP=${SOURCE}.tmp.c
                C_OUT=${SOURCE%.mkc}.c

                if [ $F -eq 1 ] || [ "$SOURCE" -nt "$C_OUT" ]; then
                        subproc ./target/debug/makec-stage0 "${MAKEC_OPT[@]}" >"$C_TMP"
                        mv "$C_TMP" "$C_OUT"
                fi

                BIN_OUT=${SOURCE%.mkc}.bin

                if [ $C -eq 1 ] && [ "$C_OUT" -nt "$BIN_OUT" ]; then
                        if [ $F -eq 1 ] || [ "$C_OUT" -nt "$BIN_OUT" ]; then
                                subproc cc -std=c99 -Wall -Wextra -Werror \
                                        -Wno-unused-function \
                                        -o "$BIN_OUT" "$C_OUT"
                        fi
                fi

                if [ $R -eq 1 ]; then
                        subproc "${SOURCE%.mkc}.bin"
                fi
        done
}

subproc() {
        echo " -> $*" >&2
        command "$@"
}

main "$@"
